using System.Collections.Generic;
using Rilisoft.MiniJson;

namespace BCW.Friends
{
	public class FriendsPlayerStorage
	{
		public const string STORAGE_FIELD_NAME = "FriendsPlayerDB";

		public static FriendsPlayerStorage instance;

		private Dictionary<string, PlayerInfo> _playerDB;

		public Dictionary<string, PlayerInfo> PlayerDB
		{
			get
			{
				Init();
				return _playerDB;
			}
		}

		private FriendsPlayerStorage()
		{
		}

		public static FriendsPlayerStorage GetInstance()
		{
			if (instance == null)
			{
				instance = new FriendsPlayerStorage();
			}
			return instance;
		}

		public void Save()
		{
			if (_playerDB.Count == 0)
			{
				return;
			}
			List<List<object>> list = new List<List<object>>();
			foreach (KeyValuePair<string, PlayerInfo> item in _playerDB)
			{
				if (!string.IsNullOrEmpty(item.Value.playerId))
				{
					list.Add(item.Value.ToList());
				}
			}
			BCWStorage.Set("FriendsPlayerDB", Json.Serialize(list));
		}

		private void Init()
		{
			if (_playerDB != null)
			{
				return;
			}
			_playerDB = new Dictionary<string, PlayerInfo>();
			string text = BCWStorage.Get<string>("FriendsPlayerDB");
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			List<object> list = Json.Deserialize(text) as List<object>;
			if (list.Count == 0)
			{
				return;
			}
			foreach (List<object> item in list)
			{
				PlayerInfo value = default(PlayerInfo);
				value.InitByList(item);
				if (!string.IsNullOrEmpty(value.playerId))
				{
					_playerDB[value.playerId] = value;
				}
			}
		}
	}
}
